<template>
  <div>
    <!-- Sidebar -->
    <div class="sidebar">
      <div style="padding: 24px 20px; border-bottom: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 18px;">快</div>
          <div style="margin-left: 12px;">
            <div style="font-weight: 600; color: #111827;">快递代拿管理系统</div>
          </div>
        </div>
      </div>

      <div style="padding: 16px 0;">
        <div class="nav-section">主菜单</div>
        <button :class="['nav-item', $route.path === '/admin/dashboard' ? 'active' : '']" @click="$router.push('/admin/dashboard')"><i class="fas fa-chart-line"></i><span>数据总览</span></button>
        <button :class="['nav-item', $route.path === '/admin/orders' ? 'active' : '']" @click="$router.push('/admin/orders')"><i class="fas fa-box"></i><span>订单管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/users' ? 'active' : '']" @click="$router.push('/admin/users')"><i class="fas fa-users"></i><span>下单者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/couriers' ? 'active' : '']" @click="$router.push('/admin/couriers')"><i class="fas fa-motorcycle"></i><span>代拿者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/finance' ? 'active' : '']" @click="$router.push('/admin/finance')"><i class="fas fa-wallet"></i><span>财务管理</span></button>

        <div class="nav-section">运营管理</div>
        <button :class="['nav-item', $route.path === '/admin/announcements' ? 'active' : '']" @click="$router.push('/admin/announcements')"><i class="fas fa-bullhorn"></i><span>公告管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/pricing' ? 'active' : '']" @click="$router.push('/admin/pricing')"><i class="fas fa-percentage"></i><span>盈利规则</span></button>
        

        <div class="nav-section">系统设置</div>
        <button :class="['nav-item', $route.path === '/admin/permissions' ? 'active' : '']" @click="$router.push('/admin/permissions')"><i class="fas fa-shield-alt"></i><span>权限管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/logs' ? 'active' : '']" @click="$router.push('/admin/logs')"><i class="fas fa-file-alt"></i><span>系统日志</span></button>
        <button :class="['nav-item', $route.path === '/admin/settings' ? 'active' : '']" @click="$router.push('/admin/settings')"><i class="fas fa-cog"></i><span>系统设置</span></button>
      </div>

      <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 20px; border-top: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; border-radius: 50%; background:#e5e7eb; display:flex; align-items:center; justify-content:center; color:#6b7280; font-weight:600;">管</div>
          <div style="margin-left: 12px; flex: 1;">
            <div style="font-weight: 500; color: #111827; font-size: 14px;">管理员</div>
            <div style="font-size: 12px; color: #9ca3af;">超级管理员</div>
          </div>
        </div>
        <button class="nav-item" @click="confirmLogout" style="margin-top:12px;"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></button>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <!-- Header -->
      <div style="background: white; border-bottom: 1px solid #e5e7eb; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between;">
        <div></div>
        <div style="position: relative;">
          <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #9ca3af;"></i>
          <input type="text" placeholder="搜索..." style="padding: 8px 12px 8px 36px; border: 1px solid #e5e7eb; border-radius: 8px; width: 240px; font-size: 14px;">
        </div>
      </div>

      <!-- Content -->
      <div style="padding: 32px;">
        <div style="margin-bottom: 32px;">
          <h1 style="font-size: 28px; font-weight: 700; color: #111827; margin-bottom: 8px;">财务管理</h1>
          <p style="color: #6b7280;">平台收入、支出及结算管理</p>
        </div>

        <!-- Financial Stats -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 24px; margin-bottom: 32px;">
          <div class="stat-card">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <div>
                <div style="color: #6b7280; font-size: 14px; margin-bottom: 8px;">本月总收入</div>
                <div style="font-size: 28px; font-weight: 700; color: #111827;">¥{{ formatMoney(stats.monthlyRevenue) }}</div>
                <div v-if="stats.growthRate > 0" style="font-size: 13px; color: #10b981; margin-top: 8px;"><i class="fas fa-arrow-up"></i> {{ stats.growthRate }}% 较上月</div>
                <div v-else-if="stats.growthRate < 0" style="font-size: 13px; color: #ef4444; margin-top: 8px;"><i class="fas fa-arrow-down"></i> {{ Math.abs(stats.growthRate) }}% 较上月</div>
                <div v-else style="font-size: 13px; color: #6b7280; margin-top: 8px;">与上月持平</div>
              </div>
              <div style="width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                <svg viewBox="0 0 24 24" width="30" height="30" aria-hidden="true">
                  <path d="M5 19h14" fill="none" stroke="#10b981" stroke-width="1.8" stroke-linecap="round"/>
                  <path d="M7 14l4-6 3 4 3-5" fill="none" stroke="#10b981" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <div>
                <div style="color: #6b7280; font-size: 14px; margin-bottom: 8px;">待结算金额</div>
                <div style="font-size: 28px; font-weight: 700; color: #111827;">¥{{ formatMoney(stats.pendingSettlement) }}</div>
                <div style="font-size: 13px; color: #6b7280; margin-top: 8px;">待处理订单 {{ stats.pendingOrderCount }} 笔</div>
              </div>
              <div style="width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                <svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true">
                  <circle cx="12" cy="12" r="7" fill="none" stroke="#f59e0b" stroke-width="1.8"/>
                  <path d="M12 8v4l2.5 2" fill="none" stroke="#f59e0b" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <div>
                <div style="color: #6b7280; font-size: 14px; margin-bottom: 8px;">已结算金额</div>
                <div style="font-size: 28px; font-weight: 700; color: #111827;">¥{{ formatMoney(stats.settled) }}</div>
                <div style="font-size: 13px; color: #6b7280; margin-top: 8px;">本月已结算 {{ stats.settledOrderCount }} 笔</div>
              </div>
              <div style="width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                <svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true">
                  <circle cx="12" cy="12" r="7" fill="none" stroke="#3b82f6" stroke-width="1.8"/>
                  <path d="M9.5 12.2l2 2 3.5-3.5" fill="none" stroke="#3b82f6" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <div>
                <div style="color: #6b7280; font-size: 14px; margin-bottom: 8px;">平台手续费</div>
                <div style="font-size: 28px; font-weight: 700; color: #111827;">¥{{ formatMoney(stats.platformFee) }}</div>
                <div style="font-size: 13px; color: #6b7280; margin-top: 8px;">{{ stats.commissionRate }}% 平台服务费</div>
              </div>
              <div style="width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                <svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true">
                  <circle cx="8" cy="8" r="2.2" fill="none" stroke="#a855f7" stroke-width="1.7"/>
                  <path d="M5 19l10-14" fill="none" stroke="#a855f7" stroke-width="1.7" stroke-linecap="round"/>
                  <circle cx="16" cy="16" r="2.2" fill="none" stroke="#a855f7" stroke-width="1.7"/>
                </svg>
              </div>
            </div>
          </div>
        </div>

        <!-- Revenue Chart with fixed height -->
        <div class="content-card" style="margin-bottom: 32px;">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px;">
            <h3 style="font-size: 18px; font-weight: 600; color: #111827;">收入趋势</h3>
            <div style="display: flex; gap: 12px;">
              <select v-model="chartDays" @change="fetchRevenueTrend()" style="padding: 6px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 14px; color: #6b7280;">
                <option :value="7">最近7天</option>
                <option :value="30">最近30天</option>
                <option :value="90">最近90天</option>
              </select>
              <button style="padding: 6px 16px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 14px;"><i class="fas fa-download"></i> 导出报表</button>
            </div>
          </div>
          <div class="chart-box"><canvas id="revenueChart"></canvas></div>
        </div>

        <!-- Transaction Records -->
        <div class="content-card" style="margin-bottom: 32px;">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px;">
            <h3 style="font-size: 18px; font-weight: 600; color: #111827;">交易记录</h3>
            <div style="display: flex; gap: 12px;">
              <select style="padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 14px; color: #6b7280;"><option>全部状态</option><option>已完成</option><option>处理中</option><option>失败</option></select>
              <input type="date" style="padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 14px; color: #6b7280;">
            </div>
          </div>
          <div style="overflow-x: auto;">
            <table class="transaction-table">
              <thead>
                <tr>
                  <th>交易编号</th>
                  <th>交易类型</th>
                  <th>关联订单</th>
                  <th>交易对象</th>
                  <th>交易金额</th>
                  <th>手续费</th>
                  <th>状态</th>
                  <th>交易时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="t in transactions" :key="t.transaction_id">
                  <td style="font-weight: 500; white-space: nowrap;">{{ t.transaction_no }}</td>
                  <td style="white-space: nowrap;">{{ t.transaction_type || '订单收入' }}</td>
                  <td style="white-space: nowrap;">{{ t.order_no }}</td>
                  <td>
                    <div style="white-space: nowrap;">{{ t.user_name || '未知用户' }}</div>
                    <div style="font-size: 12px; color: #9ca3af;">{{ t.user_phone || '-' }}</div>
                  </td>
                  <td :style="t.category === '订单收入' ? 'font-weight: 600; color: #10b981; white-space: nowrap;' : 'font-weight: 600; color: #ef4444; white-space: nowrap;'">
                    {{ t.category === '订单收入' ? '+' : '-' }}¥{{ formatMoney(t.amount) }}
                  </td>
                  <td style="color: #6b7280; white-space: nowrap;">¥{{ formatMoney(t.commission_fee || 0) }}</td>
                  <td style="white-space: nowrap;">
                    <span v-if="t.status === 1 || t.status === 'completed'" class="status-badge status-success">已完成</span>
                    <span v-else-if="t.status === 0 || t.status === 'pending'" class="status-badge status-pending">处理中</span>
                    <span v-else class="status-badge status-failed">失败</span>
                  </td>
                  <td style="color: #6b7280; white-space: nowrap;">{{ formatDate(t.created_at) }}</td>
                  <td style="white-space: nowrap;">
                    <button style="padding: 6px 12px; background: #f3f4f6; border: none; border-radius: 6px; cursor: pointer; font-size: 13px; color: #374151;">详情</button>
                  </td>
                </tr>
                <tr v-if="transactions.length === 0">
                  <td colspan="9" style="text-align: center; padding: 40px; color: #9ca3af;">暂无交易记录</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- Pagination -->
          <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 24px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
            <div style="color: #6b7280; font-size: 14px;">显示 {{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, totalRecords) }} 条，共 {{ totalRecords }} 条记录</div>
            <div style="display: flex; gap: 8px; margin-left: auto;">
              <button 
                @click="currentPage > 1 && (currentPage--, fetchTransactions())"
                :disabled="currentPage === 1"
                style="padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 6px; cursor: pointer; color: #6b7280;"
                :style="currentPage === 1 ? 'opacity: 0.5; cursor: not-allowed;' : ''"
              >上一页</button>
              <button 
                v-for="p in Math.min(5, totalPages)" 
                :key="p"
                @click="currentPage = p; fetchTransactions()"
                :style="currentPage === p ? 'padding: 8px 12px; border: 1px solid #3b82f6; background: #3b82f6; color: white; border-radius: 6px; cursor: pointer;' : 'padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 6px; cursor: pointer; color: #6b7280;'"
              >{{ p }}</button>
              <button 
                @click="currentPage < totalPages && (currentPage++, fetchTransactions())"
                :disabled="currentPage >= totalPages"
                style="padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 6px; cursor: pointer; color: #6b7280;"
                :style="currentPage >= totalPages ? 'opacity: 0.5; cursor: not-allowed;' : ''"
              >下一页</button>
            </div>
          </div>
        </div>

        <!-- Withdraw Requests -->
        <div class="content-card">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px;">
            <h3 style="font-size: 18px; font-weight: 600; color: #111827;">提现申请</h3>
            <div style="display: flex; gap: 12px;">
              <select v-model="withdrawStatusFilter" @change="fetchWithdrawRequests()" style="padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 14px; color: #6b7280;">
                <option value="">全部状态</option>
                <option value="1">待处理</option>
                <option value="2">成功</option>
                <option value="3">失败</option>
              </select>
            </div>
          </div>
          <div style="overflow-x: auto;">
            <table class="transaction-table">
              <thead>
                <tr>
                  <th>申请编号</th>
                  <th>用户ID</th>
                  <th>提现方式</th>
                  <th>提现金额</th>
                  <th>状态</th>
                  <th>创建时间</th>
                  <th>处理时间</th>
                  <th>备注</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="r in withdrawRequests" :key="r.id">
                  <td style="white-space: nowrap;">{{ r.id }}</td>
                  <td style="white-space: nowrap;">{{ r.user_id }}</td>
                  <td style="white-space: nowrap;">{{ r.method === 'wechat' ? '微信钱包' : r.method }}</td>
                  <td style="font-weight: 600; color: #111827; white-space: nowrap;">¥{{ formatMoney(r.amount) }}</td>
                  <td style="white-space: nowrap;">
                    <span v-if="r.status === 1" class="status-badge status-pending">待处理</span>
                    <span v-else-if="r.status === 2" class="status-badge status-success">成功</span>
                    <span v-else class="status-badge status-failed">失败</span>
                  </td>
                  <td style="white-space: nowrap; color: #6b7280;">{{ formatDate(r.created_at) }}</td>
                  <td style="white-space: nowrap; color: #6b7280;">{{ r.processed_at ? formatDate(r.processed_at) : '-' }}</td>
                  <td style="white-space: nowrap; color: #6b7280;">{{ r.remark || '-' }}</td>
                  <td style="white-space: nowrap;">
                    <button
                      v-if="r.status === 1"
                      @click="handleWithdrawProcessed(r.id)"
                      style="padding: 6px 12px; background: #3b82f6; color: #fff; border-radius: 6px; border: none; cursor: pointer; font-size: 13px;"
                    >已处理</button>
                    <span v-else style="font-size: 12px; color: #9ca3af;">—</span>
                  </td>
                </tr>
                <tr v-if="withdrawRequests.length === 0">
                  <td colspan="8" style="text-align: center; padding: 40px; color: #9ca3af;">暂无提现申请</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 24px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
            <div style="color: #6b7280; font-size: 14px;">显示 {{ (withdrawPage - 1) * withdrawPageSize + 1 }}-{{ Math.min(withdrawPage * withdrawPageSize, withdrawTotal) }} 条，共 {{ withdrawTotal }} 条记录</div>
            <div style="display: flex; gap: 8px; margin-left: auto;">
              <button 
                @click="withdrawPage > 1 && (withdrawPage--, fetchWithdrawRequests())"
                :disabled="withdrawPage === 1"
                style="padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 6px; cursor: pointer; color: #6b7280;"
                :style="withdrawPage === 1 ? 'opacity: 0.5; cursor: not-allowed;' : ''"
              >上一页</button>
              <button 
                v-for="p in Math.min(5, withdrawTotalPages)" 
                :key="p"
                @click="withdrawPage = p; fetchWithdrawRequests()"
                :style="withdrawPage === p ? 'padding: 8px 12px; border: 1px solid #3b82f6; background: #3b82f6; color: white; border-radius: 6px; cursor: pointer;' : 'padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 6px; cursor: pointer; color: #6b7280;'"
              >{{ p }}</button>
              <button 
                @click="withdrawPage < withdrawTotalPages && (withdrawPage++, fetchWithdrawRequests())"
                :disabled="withdrawPage >= withdrawTotalPages"
                style="padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 6px; cursor: pointer; color: #6b7280;"
                :style="withdrawPage >= withdrawTotalPages ? 'opacity: 0.5; cursor: not-allowed;' : ''"
              >下一页</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'AdminFinance',
  data() {
    return {
      stats: {
        monthlyRevenue: 0,
        growthRate: 0,
        pendingSettlement: 0,
        pendingOrderCount: 0,
        settled: 0,
        settledOrderCount: 0,
        platformFee: 0,
        commissionRate: 10
      },
      transactions: [],
      currentPage: 1,
      pageSize: 20,
      totalPages: 1,
      totalRecords: 0,
      chartDays: 7,
      withdrawRequests: [],
      withdrawPage: 1,
      withdrawPageSize: 20,
      withdrawTotal: 0,
      withdrawTotalPages: 1,
      withdrawStatusFilter: ''
    }
  },
  methods: {
    confirmLogout() {
      if (confirm('是否确认退出？')) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminInfo')
        localStorage.removeItem('userToken')
        this.$router.push('/login')
      }
    },
    formatMoney(amount) {
      return (Number(amount) || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    },
    async fetchStats() {
      try {
        const { data } = await axios.get('/api/admin/finance/stats')
        if (data && data.success) {
          this.stats = data.data || {}
        }
      } catch (e) {
        console.error('获取财务统计失败', e)
      }
    },
    async fetchTransactions() {
      try {
        const { data } = await axios.get('/api/admin/finance/transactions', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            status: '',
            startDate: '',
            endDate: ''
          }
        })
        if (data && data.success) {
          this.transactions = data.data || []
          this.totalRecords = data.total || 0
          this.totalPages = Math.ceil(this.totalRecords / this.pageSize)
        }
      } catch (e) {
        console.error('获取交易记录失败', e)
      }
    },
    async fetchRevenueTrend() {
      try {
        const { data } = await axios.get('/api/admin/finance/revenue-trend', {
          params: { days: this.chartDays }
        })
        if (data && data.success && window.Chart) {
          this.updateChart(data.data || [])
        }
      } catch (e) {
        console.error('获取收入趋势失败', e)
      }
    },
    async fetchWithdrawRequests() {
      try {
        const { data } = await axios.get('/api/admin/finance/withdraw-requests', {
          params: {
            page: this.withdrawPage,
            pageSize: this.withdrawPageSize,
            status: this.withdrawStatusFilter
          }
        })
        if (data && data.success) {
          this.withdrawRequests = data.data || []
          this.withdrawTotal = data.total || 0
          this.withdrawTotalPages = Math.ceil(this.withdrawTotal / this.withdrawPageSize) || 1
        }
      } catch (e) {
        console.error('获取提现申请列表失败', e)
      }
    },
    async handleWithdrawProcessed(id) {
      if (!id) return
      if (!confirm('确认已完成该提现并打款给代拿员？')) return
      try {
        const { data } = await axios.post(`/api/admin/finance/withdraw-requests/${id}/process`, {
          status: 2,
          remark: '管理员标记为已处理（模拟打款）'
        })
        if (!data || data.success === false) {
          alert((data && data.message) || '处理失败，请稍后再试')
          return
        }
        alert('该提现申请已标记为成功，代拿员可提现余额将相应减少（模拟）')
        this.fetchWithdrawRequests()
      } catch (e) {
        console.error('处理提现申请失败', e)
        alert('处理失败，请稍后再试')
      }
    },
    formatDate(dateStr) {
      if (!dateStr) return '-'
      try {
        return new Date(dateStr).toLocaleString('zh-CN', { 
          year: 'numeric', 
          month: '2-digit', 
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch {
        return dateStr
      }
    },
    updateChart(chartData) {
      const ctx = document.getElementById('revenueChart')
      if (!ctx) return
      
      const existingChart = window.revenueChartInstance
      if (existingChart) {
        existingChart.destroy()
      }

      // 将日期格式化为 MM-DD 短日期
      const labels = chartData.map(d => {
        if (!d.date) return ''
        const dt = new Date(d.date)
        if (Number.isNaN(dt.getTime())) return String(d.date)
        const m = String(dt.getMonth() + 1).padStart(2, '0')
        const day = String(dt.getDate()).padStart(2, '0')
        return `${m}-${day}`
      })

      window.revenueChartInstance = new window.Chart(ctx.getContext('2d'), {
        type: 'line',
        data: {
          labels,
          datasets: [
            { 
              label: '收入',
              data: chartData.map(d => d.revenue || 0),
              borderColor: '#3b82f6',
              backgroundColor: 'rgba(59,130,246,0.12)',
              tension: 0.35,
              fill: true,
              pointRadius: 3,
              pointBackgroundColor: '#3b82f6'
            },
            { 
              label: '支出',
              data: chartData.map(d => d.expense || 0),
              borderColor: '#9ca3af',
              backgroundColor: 'rgba(229,231,235,0.4)',
              tension: 0.35,
              fill: true,
              pointRadius: 3,
              pointBackgroundColor: '#9ca3af'
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: { legend: { position: 'top', align: 'end' } },
          scales: {
            y: { beginAtZero: true, grid: { color: '#f3f4f6' } },
            x: { grid: { display: false } }
          }
        }
      })
    }
  },
  mounted() {
    this.fetchStats()
    this.fetchTransactions()
    const ensureChartJs = () => new Promise((resolve) => {
      if (window.Chart) return resolve();
      const s = document.createElement('script');
      s.src = 'https://cdn.jsdelivr.net/npm/chart.js';
      s.onload = () => resolve();
      document.body.appendChild(s);
    });

    ensureChartJs().then(() => {
      this.fetchRevenueTrend()
    });

    this.fetchWithdrawRequests()
  }
}
</script>

<style scoped>
.sidebar { position: fixed; left: 0; top: 0; width: 240px; height: 100vh; background: #fff; border-right: 1px solid #e5e7eb; overflow-y: auto; }
.main-content { margin-left: 240px; min-height: 100vh; }
.nav-item { display: flex; align-items: center; padding: 12px 20px; color: #6b7280; text-decoration: none; transition: all 0.2s; cursor: pointer; width: 100%; background: transparent; border: 0; text-align: left; }
.nav-item:hover { background: #f3f4f6; color: #3b82f6; }
.nav-item.active { background: #eff6ff; color: #3b82f6; font-weight: 500; }
.nav-item i { width: 20px; margin-right: 12px; }
.nav-section { padding: 16px 20px 8px; font-size: 12px; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; }
.stat-card { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.content-card { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.chart-box { height: 320px; }
.chart-box canvas { width: 100% !important; height: 100% !important; }
.status-badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 500; }
.status-success { background: #d1fae5; color: #065f46; }
.status-pending { background: #fef3c7; color: #92400e; }
.status-failed { background: #fee2e2; color: #991b1b; }
.transaction-table { width: 100%; border-collapse: collapse; }
.transaction-table thead th { 
  background: #f9fafb; 
  padding: 12px 16px; 
  text-align: left; 
  font-weight: 600; 
  font-size: 14px; 
  color: #374151; 
  border-bottom: 2px solid #e5e7eb; 
  white-space: nowrap;
}
.transaction-table tbody td { 
  padding: 16px; 
  border-bottom: 1px solid #f3f4f6; 
  font-size: 14px; 
  color: #111827;
  vertical-align: middle;
}
.transaction-table tbody tr:hover { background: #f9fafb; }
.transaction-table tbody tr:last-child td { border-bottom: none; }
</style>
